<?php

namespace app\api\controller;

use app\admin\model\Banner;
use app\admin\model\Msgsned;
use app\common\controller\Api;
use app\common\model\Packages;
use app\common\model\PackagesUserStatus;
use app\common\model\UserPackagesConfig;
use fast\Random;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = [
        'ceshi',
        'goodsdetails',
        'imagebase64',
        'jiesuan',
        'digui',
        'laqu',
        'zqRange',
        'banner',
        'msgsend',
        'msgsend_details',
        'goods',
        'config',
        'version'
    ];
    protected $noNeedRight = ['*'];

    public function ceshi()
    {
        //卡管家
        $url                 = "https://kgj.100861.net/api/card/open/getGoodsList";
        $data['goodsStatus'] = 'on_sale';
        $data['appId']       = 'm7qu2Cq9EvM8CVQ';
        $kgj_appkey          = db('config')->where(['name' => 'kgj_appkey'])->value('value');
        $data['timeStamp']   = time();
        $data['sign']        = strtolower(md5($data['appId'].$data['timeStamp'].$kgj_appkey));

        $data_string         = json_encode($data, true);
        $ch                  = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array (
                'Content-Type: application/json',
                'App-Id:m7qu2Cq9EvM8CVQ',
                'App-Token:904b147d1ed15f4216b2e5bfc7caefb8',
            )
        );
        $result = json_decode(curl_exec($ch), true);
        dump($result);
        exit();
//                $data = cache('goods_kgj',$result);
//                exit();
        $data = cache('goods_kgj');
//        dump($data);exit();
        foreach ($data['rows'] as $k => $v) {
            $info = Packages::where(['packages_id' => $v['goodsCode'], 'platform_type' => 6])->find();
            if (!$info) {
                for ($i = 2; $i <= 3; $i++) {
                    $inser['platform_type'] = 6;
                    $inser['packages_id']   = $v['goodsCode'];
                    $inser['name']          = $v['goodsName'];
                    $inser['user_name']     = $v['goodsName'];
                    $inser['type']          = $i;
                    if (strpos($v['goodsName'], '电信') !== false) {
                        $inser['cate_id'] = 1;
                    } elseif (strpos($v['goodsName'], '联通') !== false) {
                        $inser['cate_id'] = 2;
                    } elseif (strpos($v['goodsName'], '移动') !== false) {
                        $inser['cate_id'] = 3;
                    }
                    $inser['photos']     = $v['goodsHeadImg'];
                    $inser['photoLists'] = $v['goodsDetail'];
                    $inser['rebate']     = $v['rebateJson']['activatePrice'];
                    $inser['data_json']  = json_encode($v, true);
                    Packages::create($inser);
                }

            }
        }

//        dump($result);
        exit();
        //感叹号
//        $url = "https://91haoka.cn/api/gth/order-pages2?status=100&_page=1&_page_size=20&warn_province=&operator=&province=&city=&title=&parent_name=&mine=&fetch_code=&sku=&product_name=&selling_point=";
//
//        $ch          = curl_init($url);
//        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
////        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array (
//                'Content-Type: application/json',
////                'Content-Length: '.strlen($data_string),
//                'Referer:https://91haoka.cn/gth/',
//                'X-Xsrf-Token:eyJpdiI6IkRueERzRlp6WVZIY0hJMDVHaU0waWc9PSIsInZhbHVlIjoiU3IyWmlldnNpNnRhYzM2VzI2c09YcWtVY1wvQ2djWmpTdEtkOVZtenFtZUFCcGdUUmpnWU1GRTJcL2c3WWorUkd4MWhPSGszQTJNWlhZTVo3aDdwY1IxUT09IiwibWFjIjoiOWQwMzIzM2E4YmNjYmQ4ZjZhMWYxODQ3MjRjZGNkNmQ5MDQ4OWE2ZWQ2OWNmY2RkNzcxOTFlZDg1OTM3YzgzNSJ9',
//                'Cookie:XSRF-TOKEN=eyJpdiI6IkRueERzRlp6WVZIY0hJMDVHaU0waWc9PSIsInZhbHVlIjoiU3IyWmlldnNpNnRhYzM2VzI2c09YcWtVY1wvQ2djWmpTdEtkOVZtenFtZUFCcGdUUmpnWU1GRTJcL2c3WWorUkd4MWhPSGszQTJNWlhZTVo3aDdwY1IxUT09IiwibWFjIjoiOWQwMzIzM2E4YmNjYmQ4ZjZhMWYxODQ3MjRjZGNkNmQ5MDQ4OWE2ZWQ2OWNmY2RkNzcxOTFlZDg1OTM3YzgzNSJ9; laravel_session=eyJpdiI6IkVMZjNoSjF5NDlRcmtwMkFtSWVFVmc9PSIsInZhbHVlIjoiWnRsamlMUlYwaUczbHVZUjd0NGY1bXBxZitDa1Jqc3RvaU9LakxuNVJjOEIwaFhWRUYyck9iOEp4eUU2dkFcL2t2NHY2dk5laW90SFRrOGlYcFJnRUJ3PT0iLCJtYWMiOiI2ODc1N2IwODk0ZjE1YWVjYWE3ZWVlNDI1YWJmYmZkMDI5MzY5NDlmOGJlNWM1YWMyYTcyMjI3NTY0MTExN2MwIn0%3D',
//            )
//        );
//        $result = json_decode(curl_exec($ch), true);
//        $data = cache('goods',$result);
//        $data =   cache('goods');
//        foreach ($data['data']['data'] as $k=>$v){
//            $info = Packages::where(['packages_id'=>$v['fetch_code']])->find();
//            if(!$info){
//                for ($i = 2;$i<=3;$i++){
//                    $inser['platform_type'] = 5;
//                    $inser['packages_id']   = $v['fetch_code'];
//                    $inser['name']          = $v['product_name'];
//                    $inser['user_name']     = $v['parent_title'];
//                    $inser['type']          = $i;
//                    if(strpos($v['title'],'电信') !== false){
//                        $inser['cate_id']     = 1;
//                    }elseif (strpos($v['title'],'联通') !== false){
//                        $inser['cate_id']     = 2;
//                    }elseif (strpos($v['title'],'移动') !== false){
//                        $inser['cate_id']     = 3;
//                    }
//                    $inser['photos']      = $v['image1'];
//                    $inser['photoLists'] = $v['description'];
//                    $inser['rebate']     = $v['active_commission'];
//                    $inser['data_json']  = json_encode($v,true);
//                    Packages::create($inser);
//                }
//
//            }
//
//        }
//        dump($data);
    }


    public function cc()
    {


// 输出结果
//        print_r($result);

    }

    public function laqu()
    {

        $url = "https://hao.san-jk.com/agent/index/getApiConfig";//办理套餐
// 要发送的数据
        $data = db('packages')->where(['platform_type' => 2])->select();
        $num  = -1;
        foreach ($data as $k => $v) {
            $json_arr    = json_decode($v['data_json'], true);
            $data        = array (
                'goods_id' => $json_arr['id']
            );
            $data_string = json_encode($data);
            $ch          = curl_init($url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array (
                    'Content-Type: application/json',
                    'Content-Length: '.strlen($data_string),
                    'Token:f4a522fa-c3a8-45b1-a1ba-876aba8657f3'
                )
            );
            $result = json_decode(curl_exec($ch), true);
            if (!empty($result['data']['list'][0]['acid'])) {
                $r = db('packages')->where(['id' => $v['id']])->update([
                    'packages_id'     => $result['data']['list'][0]['acid'],
                    'packages_id_two' => $v['packages_id']
                ]);
                if ($r) {
                    $num += 1;
                }
            }
        }
        dump($num);
        exit();

// 将数据转换为JSON格式
        $jsonData = json_encode($data);

        //初始化
        $ch                             = curl_init();
        $data['goods_id']               = 56;
        $params[CURLOPT_URL]            = $url;  //请求url地址
        $params[CURLOPT_HEADER]         = false; //是否返回响应头信息
        $params[CURLOPT_RETURNTRANSFER] = true;  //是否将结果返回
        $params[CURLOPT_FOLLOWLOCATION] = true;  //是否重定向
        $params[CURLOPT_USERAGENT]      = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1';
        $params[CURLOPT_POST]           = true;
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array (
            'Content-Type: application/json',
            'Content-Length: '.strlen($jsonData),
            'Token:43e56382-5b81-4d3a-8e65-cb6f35dd2834'
        ));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch);       //执行
        //执行命令
        dump($content);
        exit();
        $data = json_decode($content, true);


        foreach ($data['data']['list'] as $k => $v) {
            if ($k > 0) {
                $inser['platform_type'] = 3;
                $inser['cate_id']       = 2;//联通
                $inser['photos']        = $v['image'];
                $inser['photoLists']    = $v['image'];
                $inser['h5url']         = $v['url'];
                $inser['rebate']        = $v['agfee'];
                $inser['data_json']     = json_encode($v);
                $inser['packages_id']   = $v['id'];
                $inser['name']          = $v['name'];
                $inser['status']        = 1;
                \app\admin\model\Packages::create($inser);

            }

        }
        exit();
        $this->success('', $content);
        //关闭URL请求

//    curl_close($curl);


    }

    public function imagebase64()
    {
        $image = input('image');
        if (!$image) {
            $this->error('缺少参数');
        }
        $imageData   = file_get_contents(cdnurl( $image,true,1));
        $base64Image = base64_encode($imageData);
        $this->success('ok', $base64Image);
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        $cate_id         = input('cate_id');
        $where['status'] = 1;
        $agent_id        = input('agent_id');
        if (!$agent_id) {
            $this->error('缺少参数');
        }
        $agent_info = \app\common\model\User::where(['id' => $agent_id, 'parent_id' => $this->auth->id])->find();
        if (!$agent_info) {
            $this->error('代理不存在');
        }
        if ($cate_id) {
            $where['cate_id'] = $cate_id;
        }
        $query = \app\admin\model\Packages::where($where)->whereIn('type', '1,3');

        $goods_soldout = db('packages_user_status')->where(['agent_id' => $this->auth->id])->field('packages_id')->select();
        if ($goods_soldout) {
            $packages_id = '';
            foreach ($goods_soldout as $key => $val) {
                $packages_id .= ','.$val['packages_id'];
            }
            $packages_id = trim($packages_id, ',');
            $query       = $query->whereNotIn('id', $packages_id);
        }

        $data = $query->field('id,packages_id,zfsm,user_name as name,cate_id,photos,user_rebate as rebate,h5url,platform_type,xiadanxuzhi,card_type,xiaohu,tjyj,yyjl,user_memo')->order('is_extend desc,weigh desc')->paginate();
        $data = $this->compute($data->toArray(), $agent_id, 2);
        $this->success('请求成功', $data);
    }

    public function compute($data, $agent_id, $is_dl = 1)
    {
        $config = new UserPackagesConfig();
        foreach ($data['data'] as $k => &$v) {
            if ($is_dl == 2) {
                $v['is_soldout']  = PackagesUserStatus::where([
                    'agent_id'    => $agent_id,
                    'packages_id' => $v['id']
                ])->count();
                $v['user_rebate'] = $config->where([
                        'user_id'     => $this->auth->id,
                        'packages_id' => $v['id']
                    ])->value('money') ?? 0;
            }
//            if($this->auth->parent_id > 0){
            $config_info = $config->where(['user_id' => $agent_id, 'packages_id' => $v['id']])->find();
            if ($config_info) {
                $v['junior_rebate'] = $config_info['money'];
            } else {
                $v['junior_rebate'] = 0;
            }
//            }else{
//                $v['junior_rebate'] = $v['rebate'];
//                $v['user_rebate']   = $v['rebate'];
//            }
            if (strpos($v['photos'], 'http') === false) {
                $v['photos'] = cdnurl($v['photos'], true);
            }
            if (!$this->auth->parent_id) {
                $v['user_rebate'] = $v['rebate'];
            }
            if ($is_dl == 1 && !$this->auth->parent_id) {
                $v['junior_rebate'] = $v['rebate'];
            }
            unset($v['rebate']);
            $v['url'] = '';
        }
        return $data;
    }

    public function goods()
    {
        $cate_id         = input('cate_id');
        $where['status'] = 1;
        $where['type']   = 3;
        if ($cate_id) {
            $where['cate_id'] = $cate_id;
        } else {
            $where['is_extend'] = 2;
        }
        $name = input('name');
        if ($name) {
            $where['name|user_name|gui_address|jie_title'] = ['like', '%'.$name.'%'];
        }
        $query         = \app\admin\model\Packages::where($where);
        $goods_soldout = db('packages_user_status')->where(['agent_id' => $this->auth->id])->field('packages_id')->select();
        if ($goods_soldout) {
            $packages_id = '';
            foreach ($goods_soldout as $key => $val) {
                $packages_id .= ','.$val['packages_id'];
            }
            $packages_id = trim($packages_id, ',');
            $query       = $query->where(function ($quyer) use ($packages_id) {
                $quyer->whereNotIn('id', $packages_id);
            });

        }
        $data = $query->field('id,user_name,packages_id,jsgz,spxz,name,cate_id,photos,user_rebate as rebate,monthly,flow,call_minutes,pact,demand,age,is_extend,platform_type,status,epact_set_meal,ciyue_set_meal,xiadanxuzhi,card_type,xiaohu,zfsm,tjyj,yyjl,user_memo,junior_contribution,pplots_profit,jie_title,jie_content,one_commission,pplots_yunying_profit')->order('is_extend desc,weigh desc')->paginate();
        $data = $this->compute($data->toArray(), $this->auth->id);
        foreach ($data['data'] as $k => &$v) {
            $v['web_url_text'] = 'https://'.$_SERVER['HTTP_HOST'].'/qing/#/pages/order/order_details?id='.$v['id'].'&agid='.$this->auth->id;
            if (strpos($v['photos'], 'http') === false) {
                $v['photos'] = cdnurl($v['photos'], true);
            }
            $v['pplots_profit'] = (int)$v['pplots_profit'];
        }

        $config          = db('config')->where(['name' => 'sxj_tongzhi'])->find();
        $data['tongzhi'] = $config['value'];
        $user_msg        = db('msg_status')->where([
            'user_id'   => $this->auth->id,
            'config_id' => $config['id']
        ])->find();
        if ($user_msg) {
            $data['flag'] = false;
        } else {
            $inser['user_id']    = $this->auth->id;
            $inser['config_id']  = $config['id'];
            $inser['createtime'] = date('Y-m-d H:i:s');
            db('msg_status')->insert($inser);
            $data['flag'] = true;
        }
        $this->success('ok', $data);
    }

    public function goodsdetails()
    {
        $ids = input('packages_id');
        if (!$ids) {
            $this->error('缺少参数');
        }
        $info = Packages::where(['id' => $ids])->find()->toArray();
        if (!$info) {
            $this->error('产品不存在');
        }
        if ($info['status'] != 1) {
            $this->error('产品已被下架');
        }
        if ($info['platform_type'] == 1) {
            if ($info['data_json']) {
                $data = json_decode($info['data_json'], true);
            } else {
                $photos = $info['photos'];
                unset($info['photos']);
                $data                       = $info;
                $data['theme_config']['bg'] = "#000000";
                $arr                        = explode(',', $info['photoLists']);
                foreach ($arr as $k => $v) {
                    if (strpos($v, 'http') === false) {
                        $arr[$k] = cdnurl($v, true);
                    }
                }
                if (strpos($photos, 'http') === false) {
                    $photos = cdnurl($photos, true);
                }
                $data['theme_config']['photoLists'] = $arr;
                $data['photos'][0]                  = $photos;
            }

            if ($info['cate_id'] == 4) {
                $data['opText'] = '广电';
            } else {
                if ($info['cate_id'] == 5) {
                    $data['opText'] = '宽带';
                }
            }
            $data['platform_type'] = $info['platform_type'];

        } else {
            if ($info['cate_id'] == 1) {
                $info['opText'] = '电信';
            } else {
                if ($info['cate_id'] == 2) {
                    $info['opText'] = '联通';
                } else {
                    if ($info['cate_id'] == 3) {
                        $info['opText'] = '移动';
                    } else {
                        if ($info['cate_id'] == 4) {
                            $info['opText'] = '广电';
                        } else {
                            if ($info['cate_id'] == 5) {
                                $info['opText'] = '宽带';
                            }
                        }
                    }
                }
            }
            $photos = $info['photos'];
            unset($info['photos']);
            $data                       = $info;
            $data['theme_config']['bg'] = "#000000";
            $arr                        = explode(',', $info['photoLists']);
            foreach ($arr as $k => $v) {
                if (strpos($v, 'http') === false) {
                    $arr[$k] = cdnurl($v, true);
                }
            }
            if (strpos($photos, 'http') === false) {
                $photos = cdnurl($photos, true);
            }
            $data['theme_config']['photoLists'] = $arr;
            $data['photos'][0]                  = $photos;
        }
        $data['name'] = $info['user_name'];
        $data['spxz'] = $info['spxz'];
        $data['jsgz'] = $info['jsgz'];
        $this->success('ok', $data);
    }

    /**
     * 下架
     */
    public function soldout()
    {
        $ids      = input('ids');
        $agent_id = input('agent_id');
        $status   = input('status');
        if (!$agent_id || !$ids || !in_array($status, [1, 2])) {
            $this->error('参数错误');
        }
        if ($status == 1) {
            $params['agent_id']    = $agent_id;
            $params['packages_id'] = $ids;
            PackagesUserStatus::create($params);
        } else {
            PackagesUserStatus::where(['agent_id' => $agent_id, 'packages_id' => $ids])->delete();
        }
        $this->success('ok');
    }

    public function zqRange()
    {
        $model       = new \app\admin\model\Packages();
        $agent_id    = input('agent_id');
        $packages_id = input('packages_id');
        $config      = UserPackagesConfig::where(['user_id' => $this->auth->id, 'packages_id' => $packages_id])->find();
        if ($config) {
            $day = $config['day'];
        } else {
            $day = $model->where(['id' => $packages_id])->value('day');
        }
        $list = $model->getDayList();
        $arr  = [];
        $num  = -1;
        foreach ($list as $k => $v) {
            if ($k >= $day) {
                $num++;
                $arr[$num]['id']   = $k;
                $arr[$num]['name'] = $v;
            }

        }
        $this->success('ok', $arr);
    }


    public function config()
    {
        $ids    = input('id');
        $contet = '';
        if ($ids) {
            $model  = new Msgsned();
            $info   = $model->where(['id' => $ids])->find();
            $contet = $info['content'];
        }
        $hehuoren             = db('config')->where(['name' => 'user_partner_content'])->value('value');
        $user_yongjin_content = db('config')->where(['name' => 'user_yongjin_content'])->value('value');
        $user_yztc_content    = db('config')->where(['name' => 'user_yztc_content'])->value('value');
        $user_xdbd_content    = db('config')->where(['name' => 'user_xdbd_content'])->value('value');
        $tgyj                 = db('config')->where(['name' => 'tgyj'])->value('value');
        $operate_jiangli      = db('config')->where(['name' => 'operate_jiangli'])->value('value');
        $xiaoqu_memo          = db('config')->where(['name' => 'xiaoqu_memo'])->value('value');
        $quxian_memo          = db('config')->where(['name' => 'quxian_memo'])->value('value');
        $baoxiao              = db('config')->where(['name' => 'baoxiao_content'])->value('value');
        $this->success('ok', [
            'hehuoren'             => $hehuoren,
            'user_yongjin_content' => $user_yongjin_content,
            "user_yztc_content"    => $user_yztc_content,
            'content'              => $contet,
            'user_xdbd_content'    => $user_xdbd_content,
            'tgyj'                 => $tgyj,
            'operate_jiangli'      => $operate_jiangli,
            'xiaoqu_memo'          => $xiaoqu_memo,
            'quxian_memo'          => $quxian_memo,
            'baoxiao'              => $baoxiao
        ]);
    }

    public function banner()
    {
        $model = new Banner();
        $data  = $model->order('weigh desc')->select();
        $this->success('ok', $data);
    }

    public function banner_details()
    {
        $ids = input('ids');
        if (!$ids) {
            $this->error('缺少参数');
        }
        $info = Banner::where(['id' => $ids])->find();
        $this->success('ok', $info);
    }

    public function msgsend(){
        $model = new Msgsned();
        $m_type = input('m_type',1);
        $ids    = input('ids');
        if($ids){
            $where['id'] = $ids;
        }else{
            $where['type'] = 2;
            $where['m_type'] = $m_type;
        }
        $data  = $model->where($where)->order('weigh desc')->select();
        $this->success('ok',$data);
    }

    public function msgsend_details()
    {
        $model = new Msgsned();
        $ids   = input('ids');
        if (!$ids) {
            $this->error('缺少参数');
        }
        $info = $model->where(['id' => $ids])->find();
        $this->success('ok', $info);
    }

    /**
     * 关于系统
     */

    public function version()
    {
        $info            = db('version')->order('id desc')->find();
        $info['logo']    = cdnurl(db('config')->where(['name' => 'logo'])->value('value'),true,2);
        $info['eserved'] = "Copyright©2022 All Rights Reserved";
        $this->success('ok', $info);
    }

    /**
     * @menu 详情
     * @Author:男人的坏
     * @Date:2024-05-12 17:59
     */

    public function msgsendInfo(){
        $model = new Msgsned();
        $ids = input('ids');
        $data  = $model->where(['id'=>$ids])->order('weigh desc')->find();
        $this->success('ok',$data);
    }

}
